/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.common.utils;

import com.chinamobile.cmss.lakehouse.common.constants.CommonVar;
import com.chinamobile.cmss.lakehouse.common.enums.Status;

import java.text.MessageFormat;
import java.util.Base64;

import com.alibaba.druid.sql.SQLUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SqlDruidUtil {

    /**
     * format sql
     *
     * @param query  sql
     * @param dbType supported for mysql oracle mariadb postgresql sqlserver
     * @return upper case and split line
     */
    public static String formattedSql(String query, String dbType) {
        log.debug("Format sql:{} of dbType:{}", query, dbType);
        // use lowerCase dbType
        return SQLUtils.format(query, dbType.toLowerCase());
    }

    /**
     * decode sql (in case of browser incompatible, frontend use encode sql)
     *
     * @param encodedSql encode sql
     * @return decode sql
     */
    public static String decodeSql(String encodedSql) {
        Base64.Decoder decoder = Base64.getDecoder();
        String decodedSql;
        try {
            decodedSql = new String(decoder.decode(encodedSql), CommonVar.UTF_8);
            log.info("before decode: {}, after decode：{}", encodedSql, decodedSql);
            return decodedSql;
        } catch (Exception ex) {
            log.error("decode error, sql are ：{}", encodedSql);
            String msg = MessageFormat.format(Status.SQL_CONSOLE_SQL_DECODE_ERROR.getMessage(), encodedSql);
            throw new ServiceException(msg, ex);
        }
    }
}
